package com.ir.slassm.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ir.slassm.vo.NameValueVO;

public class NameValueDAO {
	Log logger = LogFactory.getLog(NameValueDAO.class.getName());
	
	@SuppressWarnings("unchecked")
	public List<NameValueVO> findByGroup(String group) {
		List<NameValueVO> results = new ArrayList<NameValueVO>();
		String sql = "keyGroup == groupParam";
		
		Object[] params = new Object[] {group};
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance(); 
		Query q = pm.newQuery(NameValueVO.class, sql);
		q.declareParameters("String groupParam");
		q.setOrdering("keyGroup desc");
		
		try {
			results = (List<NameValueVO>)pm.detachCopyAll((List<NameValueVO>)q.executeWithArray(params));
		} finally {
			pm.close();
		}
		
		return results;
	}
	
	@SuppressWarnings("unchecked")
	public List<NameValueVO> findByGroupName(String group, String name) {
		List<NameValueVO> results = new ArrayList<NameValueVO>();
		String sql = "keyGroup == groupParam && keyName == nameParam";
		
		Object[] params = new Object[] {group, name};
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance(); 
		Query q = pm.newQuery(NameValueVO.class, sql);
		q.declareParameters("String groupParam, String nameParam");
		q.setOrdering("keyGroup, keyName desc");
		
		try {
			results = (List<NameValueVO>)pm.detachCopyAll((List<NameValueVO>)q.executeWithArray(params));
		} finally {
			pm.close();
		}
		
		return results;
	}
	
	public void save(NameValueVO vo) throws Throwable {
		logger.info("save Enter.");
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance(); 
		try {
			pm.makePersistent(vo);
		} catch(Throwable t) {
			logger.warn("Failed to persist Name Value: " + t.getMessage());
			throw t;
		} finally {
			pm.close();
		}
		logger.info("save Exit.");
	}
	
	public void delete(NameValueVO vo) throws Throwable {
		logger.info("delete Enter.");
		
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance();
		try {
			pm.deletePersistent(vo);
		} catch(Throwable t) {
			logger.error("Failed to delete Name Value.", t);
			throw t;
		} finally {
			pm.close();
		}
		logger.info("delete Exit.");
	}
	
	public void delete(List<NameValueVO> voList) throws Throwable {
		logger.info("delete Enter.");
		
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance();
		try {
			pm.deletePersistentAll(voList);
		} catch(Throwable t) {
			logger.error("Failed to delete all Name Values from the list.", t);
			throw t;
		} finally {
			pm.close();
		}
		logger.info("delete Exit.");
	}
	
}
